package br.com.tarlis.core.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public abstract class ClientAction {
	
	private Map<String, Object> parameters;
	private String action;
	
	public abstract void before();
	public abstract void after();
	
	public ClientAction() {
		this.action = getClass().getName()
				.replaceFirst("\\.client\\.", "\\.server\\.");
	}
	
	public ClientAction(String action) {
		this.action = action;
	}
	
	public String getAction() {
		return action;
	}
	
	public void call() {
		before();
		ActionService.Util.getInstance()
			.doAction(getAction(), 
					  parameters, 
					  new AsyncCallback<Map<String,Object>>() {
						
						@Override
						public void onSuccess(Map<String, Object> result) {
							setParameters(result);
							after();
						}
						
						@Override
						public void onFailure(Throwable caught) {
							showError(caught);
						}
					});
	}

	private void showError(Throwable caught) {
		caught.printStackTrace();
		Window.alert(caught.getMessage());
	}
		
	public Map<String, Object> getParameters() {
		if (parameters == null) {
			parameters = new HashMap<String, Object>();
		}
		return parameters;
	}
	
	public void setParameters(Map<String, Object> parameters) {
		this.parameters = parameters;
	}

	public void clearParameters() {
		getParameters().clear();
	}

	public boolean containsParameterKey(String key) {
		return getParameters().containsKey(key);
	}

	public boolean containsParameterValue(Object value) {
		return getParameters().containsValue(value);
	}

	public Object getParameter(String key) {
		return getParameters().get(key);
	}

	public Object addParameter(String key, Object value) {
		return getParameters().put(key, value);
	}

	public void putAllParameters(Map<? extends String, ? extends Object> m) {
		getParameters().putAll(m);
	}

	public Object removeParameter(String key) {
		return getParameters().remove(key);
	}

	public int parametersSize() {
		return getParameters().size();
	}

}
